import { Image, InfiniteScroll, List } from 'antd-mobile'
// mock数据
import {fetchListAPI,ListRes} from '@/apis/list'
import { useEffect } from 'react'
import { useState } from 'react'
import { useNavigate } from 'react-router'

type Props = {
    channelId:string
}




const HomeList = (props:Props) => {

    // 开关 标记当前是否还有新数据
    const [hasMore, setHasMore] = useState(true)

    const {channelId} = props
    // 获取列表数据
    const [listRes,setListRes] = useState<ListRes>({
        results:[],
        pre_timestamp:'' + new Date().getTime(),
    })

    // 加载更多
    const loadMore = async () => {
      // 编写加载下页的核心逻辑
      console.log('加载更多')

      try {
        const res = await fetchListAPI({
          channel_id: channelId,
          timestamp: listRes.pre_timestamp,
        })
        // 拼接新数据
        setListRes({
          results: [...listRes.results,...res.data.data.results],
          pre_timestamp: res.data.data.pre_timestamp
        })
        if(res.data.data.results.length === 0){
          setHasMore(false)
        }
      } catch (error) {
        throw new Error('fetch list error')
      }
    }
    
    const navigate = useNavigate()
    const goToDetail = (id:string) => {
      console.log('跳转到详情页')
      navigate(`/detail?id=${id}`)
    }
    


    useEffect(() => {
      async function getList() {
        try {
          const res = await fetchListAPI({
            channel_id: channelId,
            timestamp: '' + new Date().getTime(),
          })
          setListRes(res.data.data)
        } catch (error) {
          throw new Error('fetch list error')
        }
      }
      getList()
    }, [channelId])



  return (
    <>
      <List>
        {listRes.results.map((item) => (
          <List.Item
            onClick={() => goToDetail(item.art_id)}
            key={item.art_id}
            prefix={
              <Image
                src={item.cover.images?.[0]}
                style={{ borderRadius: 20 }}
                fit="cover"
                width={40}
                height={40}
              />
            }
            description={item.pubdate}
            >
            {item.title}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10} />
    </>
  )
}

export default HomeList